﻿using MathNet.Numerics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Wpf.Ui;
using XC.WpfHost.Services.Contracts;
using XC.WpfHost.Views;
using XC.WpfHost.Views.Pages;

namespace XC.WpfHost.Services
{
    public class ApplicationHostService : IHostedService
    {
        private readonly IServiceProvider _serviceProvider;

        public ApplicationHostService(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        /// <summary>
        /// Triggered when the application host is ready to start the service.
        /// </summary>
        /// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await HandleActivationAsync();
        }

        /// <summary>
        /// Triggered when the application host is performing a graceful shutdown.
        /// </summary>
        /// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await Task.CompletedTask;
        }

        /// <summary>
        /// Creates main window during activation.
        /// </summary>
        private  Task HandleActivationAsync()
        {
            if (Application.Current.Windows.OfType<LoginWin>().Any())
            {
                return Task.CompletedTask;
            }

            IWindow loginWin = _serviceProvider.GetRequiredService<IWindow>();
            loginWin?.Show();

            return Task.CompletedTask;
        }
    }

}
